﻿using System;
using System.Collections.Generic;
using System.Linq;
using ControleRepresentanteSync.Logic;

namespace ControleRepresentanteSync.Application.SimpleSync
{
    abstract class SimpleSyncContentPresenter<TViewModel, TModel, TItem, TContract> : PresenterBase<TViewModel>
        where TViewModel : ISimpleSyncContentViewModel<TModel, TItem, TContract>
        where TItem : ISimpleSycItem<TContract> 
        where TContract : class
    {
        protected SimpleSyncContentPresenter(TViewModel viewModel, TModel model, IEnumerable<TItem> items)
            : base(viewModel)
        {
            ViewModel.Model = model;
            ViewModel.Actions.Add(SyncAction.CreateNew);
            ViewModel.Actions.Add(SyncAction.Merge);
            ViewModel.Action = SyncAction.CreateNew;

            foreach (TItem item in items)
            {
                ViewModel.Targets.Add(item);
            }
            ViewModel.Target = ViewModel.Targets.FirstOrDefault();

            UpdateIsValid();

            ViewModel.TargetChanged += ViewModelTargetChanged;
            ViewModel.ActionChanged += ViewModelActionChanged;
        }

        private void ViewModelActionChanged(object sender, EventArgs e)
        {
            UpdateIsValid();
        }

        private void ViewModelTargetChanged(object sender, EventArgs e)
        {
            UpdateIsValid();
        }

        private void UpdateIsValid()
        {
            ViewModel.IsValid = ViewModel.Action == SyncAction.CreateNew || ViewModel.Target.Contract != null;
        }

        public override void Dispose()
        {
            base.Dispose();
            ViewModel.TargetChanged -= ViewModelTargetChanged;
            ViewModel.ActionChanged -= ViewModelActionChanged;
        }
    }
}
